package com.njth.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import java.awt.Image;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;


public class FileAssistant  implements Serializable{
	static final long serialVersionUID=200832718L;
	
	public static Map<String,Object> fileUpload(HttpServletRequest request, File uploadAbsolutDirectory){
		if(!uploadAbsolutDirectory.exists())
			uploadAbsolutDirectory.mkdir();
		Map<String,Object> map=new HashMap<String,Object>();
		
		String allowedType=Config.getConfigProperty("allowedType");
		
		DiskFileItemFactory factory=new DiskFileItemFactory();
		factory.setSizeThreshold(Integer.parseInt(Config.getConfigProperty("uploadCachSize")));
		
		File tempAbsolutPath = new File(Config.getContenAbsolutPath()
				+Config.getConfigProperty("uploadTempPath"));
		
		factory.setRepository(tempAbsolutPath);
		ServletFileUpload upload=new ServletFileUpload(factory);
		upload.setFileSizeMax(Long.parseLong(Config.getConfigProperty("uploadMaxSize")));
		
		try {
			List<FileItem> fileItems=upload.parseRequest(request);
			
			Iterator<FileItem> it=fileItems.iterator();
			while(it.hasNext()){
				FileItem item=it.next();
				String fieldName=item.getFieldName();
				if(!item.isFormField()){
					String name=item.getName();
					
					long size=item.getSize();
					
					String[] splits=name.split("\\.");
					String postfix=splits[splits.length-1];
					if(name==null || !allowedType.contains(postfix.toLowerCase()) || name.trim()=="" ||size==0){
						continue;
					}
					
					String newName=renameFile(name);
					File newFile=new File(uploadAbsolutDirectory.getAbsolutePath(),newName);
					
					item.write(newFile);
					map.put(fieldName, newFile);
				}else{
					map.put(fieldName, new String(item.getString().getBytes("iso-8859-1"),"utf-8"));
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		return map;
	}
	/*
	public static String fileUpload(UploadedFile file, File uploadAbsolutDirectory,
				HttpSession session){
		if(!uploadAbsolutDirectory.exists())
			uploadAbsolutDirectory.mkdir();
		Date time=new Date();
		double st=time.getTime();
		String fileName=file.getName();
		double totalSize=file.getSize();
		DecimalFormat df=new DecimalFormat("#0.0%");
		
		String newName=renameFile(fileName);
		File newFile=new File(uploadAbsolutDirectory, newName);
		try {
			InputStream fileInput=file.getInputStream();
			FileOutputStream fileOutput=new FileOutputStream(newFile);
			
			byte[] buff=new byte[1024];
			int read=0;
			while((read=fileInput.read(buff, 0, buff.length))!=-1){
				
				fileOutput.write(buff, 0, read);
				double currentSize=newFile.length();
				double status=currentSize/totalSize;
				String percent=df.format(status);
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		double et=new Date().getTime();
		double rst=et-st;
		double rss=rst/1000;
		String rstr=null;
		if(rss>1){
			rstr=rss+"秒";
		}else{
			rstr=rst+"毫秒";
		}
		System.out.println("@@@@@@_jmt--------上传文件*"+newName+"*用时："+rstr);
		String rs=newName;
		
		return rs;
	}
	*/
	/**
	 * 重命名文件
	 * @param fileName
	 * @return
	 */
	public static String renameFile(String file){
		String fileName=new String(file);
		if(file.contains(":\\")){
			fileName=file.substring(file.lastIndexOf("\\"));
		}else if(file.startsWith("/")){
			fileName=file.substring(file.lastIndexOf("/"));
		}
		
		String extName=fileName.substring(fileName.lastIndexOf('.')).toLowerCase();
		StringBuilder newName=new StringBuilder();
		
		newName.append(System.currentTimeMillis());
		newName.append(extName);
		String rs=newName.toString().replace(" ", "_");
			
		return rs;
	}
	

}
